import logging
import os

class LoggerManager:
    _instance = None  # 单例实例

    def __new__(cls, name=__name__, log_file=None, log_level=logging.INFO):
        if cls._instance is None:
            cls._instance = super(LoggerManager, cls).__new__(cls)
            cls._instance._initialize(name, log_file, log_level)
        return cls._instance

    def _initialize(self, name, log_file, log_level):
        """
        初始化日志器，支持文件日志和控制台日志。
        """
        self.logger = logging.getLogger(name)
        if not self.logger.handlers:  # 确保只添加一次处理器
            # 创建控制台日志处理器
            console_handler = logging.StreamHandler()
            console_formatter = logging.Formatter(
                "%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(funcName)s - line:%(lineno)d - %(message)s"
            )
            console_handler.setFormatter(console_formatter)

            self.logger.addHandler(console_handler)

            # 创建文件日志处理器（可选）
            if log_file:
                os.makedirs(os.path.dirname(log_file), exist_ok=True)
                file_handler = logging.FileHandler(
                    log_file, 
                    encoding='utf-8-sig',  # 添加BOM头
                    mode='w'  # 确保每次新建文件
                )
                file_formatter = logging.Formatter(
                    "%(asctime)s - %(name)s - %(levelname)s - %(filename)s - %(funcName)s - line:%(lineno)d - %(message)s"
                )
                file_handler.setFormatter(file_formatter)
                self.logger.addHandler(file_handler)

            self.logger.setLevel(log_level)

    def get_logger(self):
        """
        获取日志器实例。
        """
        return self.logger
